package com.huixue.cn.ztej.api.controller;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.huixue.cn.ztej.bean.Results;
import com.huixue.cn.ztej.bean.TGoods;
import com.huixue.cn.ztej.bean.TOrderInfo;
import com.huixue.cn.ztej.bean.TStudentExercises;
import com.huixue.cn.ztej.bean.TTudentInfo;
import com.huixue.cn.ztej.controller.BaseController;
import com.huixue.cn.ztej.service.TGoodsService;
import com.huixue.cn.ztej.service.TOrderService;
import com.huixue.cn.ztej.service.TPurchaseRecordService;
import com.huixue.cn.ztej.service.TStudentExercisesService;
import com.huixue.cn.ztej.service.TTudentService;
import com.huixue.cn.ztej.utils.DateUtil;
import com.huixue.cn.ztej.utils.RandomUtil;
import com.huixue.cn.ztej.utils.SystemContents.API_RETURN_STATUS;
import com.huixue.cn.ztej.utils.framwork.JacksonUtil;
import com.huixue.cn.ztej.weixin.push.PushItem;
import com.huixue.cn.ztej.weixin.push.PushMessage;
import com.huixue.cn.ztej.weixin.util.WeixinHelper;
import com.huixue.cn.ztej.bean.TPurchaseRecord;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/api/torder")
public class ApiOrderController extends BaseController {
	@Autowired(required = true)
	private TTudentService sTudentService;
	
	@Autowired(required = true)
	private TOrderService tOrderService;
	
	@Autowired(required = true)
	private TGoodsService tGoodsService;
	
	@Autowired(required = true)
	private TPurchaseRecordService tpurchaseRecordService;
	
	@Autowired(required = true)
	private TStudentExercisesService tStudentExercisesService;
	
	
	@RequestMapping(value = "/findAllGoods",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String findAllGoods(HttpServletRequest request,HttpServletResponse response) {
		Map<String,Object> map = new HashMap<String,Object>();
		String subjectId = request.getParameter("subjectId");
		String goodType = request.getParameter("goodType");
		if(StringUtil.isEmpty(subjectId)){
			map.put("subjectId", subjectId);
		}
		if(StringUtil.isEmpty(goodType)){
			map.put("goodType", goodType);
		}
		List<TGoods> list = tGoodsService.list(map);
		Results results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(list);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/reserveOrder",produces="application/json;charset=UTF-8",method=RequestMethod.POST)
	@ResponseBody
	public String reserveOrder(@RequestBody TOrderInfo info,RedirectAttributes attrs ) {
		Results results = null;
		if(info.getOpenId()==null 
			|| StringUtil.isEmpty(info.getOpenId())
			||info.getOrderCount()==null 
			||info.getGoodsId()==null){
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "参数必填！");
			return JSON.toJSONString(results);
		}
		String openId = info.getOpenId();
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MINUTE, 120);
		TTudentInfo tti =  sTudentService.findbyOpenId(openId);
		if(tti==null){
			results = new Results(API_RETURN_STATUS.USERNOEXIST_ERROR.value(),"用户不存在","");
			return new JacksonUtil().getJson(results);
		}
		TGoods goods = tGoodsService.getInfo(info.getGoodsId());
		info.setUserId(tti.getId());
		info.setUserName(tti.getName());
		info.setSubjectId(goods.getSubjectId()+"");
		
		//info.setOrderCode(openId.substring(openId.length()-7, openId.length()-1)+System.currentTimeMillis());
		//订单号生成规则 科目+类型+时间戳+随机数
		String code = goods.getSubjectId()+""+goods.getGoodType()+Long.toHexString(System.currentTimeMillis())+RandomUtil.makeRandomString(4);
		info.setOrderCode(code.toUpperCase());
		info.setOrderPrice(goods.getGoodPrice().multiply(new BigDecimal(info.getOrderCount())));
		info.setCreateTime(new Date());
		info.setStatus(1);
		info.setOrderPhone(tti.getPhone());
		info.setTermTime(c.getTime());
		tOrderService.save(info);
		info = tOrderService.selectByOrderCode(info.getOrderCode());
		results = new Results(API_RETURN_STATUS.NORMAL.value(), "保存成功！");
		results.setData(info);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/findOwnOrders/{openId}",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String findOwnOrders(@PathVariable ("openId")String openId,RedirectAttributes attrs ) {
		Results results = null;
		if(StringUtil.isEmpty(openId)){
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "openId为空！");
			return JSON.toJSONString(results);
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("openId", openId);
		List<TOrderInfo> list = tOrderService.findlist(map);
		results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(list);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/findOwnOrderById/{orderId}",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String findOwnOrderById(@PathVariable ("orderId")String orderId,RedirectAttributes attrs ) {
		Results results = null;
		if(StringUtil.isEmpty(orderId)){
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "orderId为空！");
			return JSON.toJSONString(results);
		}
		TOrderInfo order = tOrderService.getInfo(Integer.parseInt("orderId"));
		results = new Results(API_RETURN_STATUS.NORMAL.value(),"查询成功");
		results.setData(order);
		return JSON.toJSONString(results);
	}
	
	@RequestMapping(value = "/toPayOrderSuccess/{orderId}/{formId}",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String toPayOrderSuccess(@PathVariable ("orderId")Integer orderId,@PathVariable ("orderId")String formId,
			RedirectAttributes attrs) {
		
		Results results = null;
		if(orderId<=0){
			results = new Results(API_RETURN_STATUS.PARA_ERROR.value(), "orderId为空！");
			return JSON.toJSONString(results);
		}
		TOrderInfo info = tOrderService.getInfo(orderId);
	
		TOrderInfo order= new TOrderInfo();
		order.setId(info.getId());
		order.setStatus(3);
		tOrderService.update(order);
		
		//保存购买记录
		//info.getOpenId()
		TPurchaseRecord record = new TPurchaseRecord();
		record.setOpenId(info.getOpenId());
		record.setOrderId(info.getId());
		record.setOrderCode(info.getOrderCode());
		record.setStudentId(info.getUserId());
		record.setSubjectId(Integer.valueOf(info.getSubjectId()));
		record.setOrderCount(info.getOrderCount());
		record.setOrderPrice(info.getOrderPrice());
		record.setCreateTime(info.getCreateTime());
		record.setStudentname(info.getUserName());
		tpurchaseRecordService.save(record);
		//保存学员次数
		TStudentExercises re = new TStudentExercises();
		re.setStudentId(info.getUserId());
		re.setSubjectId(Integer.valueOf(info.getSubjectId()));
		TStudentExercises ts = tStudentExercisesService.selectByExercises(re);
		if(ts!=null){
			ts.setExercisesNumber(ts.getExercisesNumber()+info.getOrderCount());
			tStudentExercisesService.update(ts);
		}else{
			re.setExercisesNumber(info.getOrderCount());
			tStudentExercisesService.save(re);
		}
		
		//推送消息
		//pushMessage(info,formId);
		results = new Results(API_RETURN_STATUS.NORMAL.value(),"更新成功");
		return JSON.toJSONString(results);
	}
	
	private void pushMessage(TOrderInfo orderInfo,String formid){
		PushMessage msg = new PushMessage();
		msg.setTouser(orderInfo.getOpenId());
		//推送模板
		msg.setTemplate_id("-qLUi5ywgd3Fqe34OqlUXdKM4Fc7X-n9_KBw_yebjew");
		//formid--表单生成
		msg.setForm_id(formid);
		Map<String,PushItem> map = new HashMap<String,PushItem>();
		PushItem pushItem1 = new PushItem("12233344", "#3A3A3A");
		map.put("keyword1", pushItem1);
		
		PushItem pushItem2 = new PushItem(orderInfo.getOrderPrice()+"元", "#3A3A3A");
		map.put("keyword2", pushItem2);
		
		PushItem pushItem3 = new PushItem(DateUtil.transfromDateToString("yyyy-MM-dd",orderInfo.getCreateTime()), "#3A3A3A");
		map.put("keyword3", pushItem3);
		
		PushItem pushItem4 = new PushItem(orderInfo.getSubjectId(), "#3A3A3A");
		map.put("keyword4", pushItem4);
		msg.setData(map);
		
		WeixinHelper.pushMessage(msg);
	}
	
	
	/*public static void main(String[] args) {
		//String accessToken = WeixinUtil.getAccessToken(Constant.AppID, Constant.AppSecret);
		//System.out.println("========accessToken====="+accessToken);
		PushMessage msg = new PushMessage();
		msg.setTouser("oB-oR0UE8BgWSgWtuVNDGRxQKbSY");
		//推送模板
		msg.setTemplate_id("-qLUi5ywgd3Fqe34OqlUXdKM4Fc7X-n9_KBw_yebjew");
		//formid--表单生成
		msg.setForm_id("1510222810354");
		Map<String,PushItem> map = new HashMap<String,PushItem>();
		PushItem pushItem1 = new PushItem("12233344", "#3A3A3A");
		map.put("keyword1", pushItem1);
		
		PushItem pushItem2 = new PushItem("30元", "#3A3A3A");
		map.put("keyword2", pushItem2);
		
		PushItem pushItem3 = new PushItem("2015年01月05日", "#3A3A3A");
		map.put("keyword3", pushItem3);
		
		PushItem pushItem4 = new PushItem("粤海喜来登酒店", "#3A3A3A");
		map.put("keyword4", pushItem4);
		msg.setData(map);
		String json = new JacksonUtil().getJson(msg);
		System.out.println(json);
		
		JSONObject result = pushMessage(msg);
		System.out.println(result.toString());
		
	}*/
	
	
}
